<template>
  <div>
    <div class="add_container">
      <el-form ref="formRef" v-loading="loading" :model="form" :rules="rules" label-width="220px">
        <!-- 产品ID -->
        <el-form-item :label="t('productId')" prop="product_id">
          <el-select v-model="form.product_id" :placeholder="t('pleaseSelect')" :disabled="isView">
            <el-option
              v-for="product in productList"
              :key="product.product_id"
              :label="product.product_name"
              :value="product.product_id">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 还款配置ID -->
        <!--        <el-form-item label="还款配置ID" prop="pay_config_id">
                  <el-input v-model="form.pay_config_id" maxlength="32" placeholder="请输入还款配置ID"
                            :disabled="isView"></el-input>
                </el-form-item>-->

        <!-- 历史贷款次数最低 -->
        <el-form-item :label="t('historyMinTimes')" prop="loan_num_min">
          <el-input-number v-model="form.loan_num_min" :min="-1"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>
        <!-- 历史贷款次数最高 -->
        <el-form-item :label="t('historyMaxTimes')" prop="loan_num_max">
          <el-input-number v-model="form.loan_num_max" :min="-1"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>
        <!-- 最大金额 -->
        <el-form-item :label="t('maxAmount')" prop="amount_max">
          <el-input-number v-model="form.amount_max" :min="0"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>

        <!-- 最小金额 -->
        <el-form-item :label="t('minAmount')" prop="amount_min">
          <el-input-number v-model="form.amount_min" :min="0"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>

        <!-- 步长 -->
        <el-form-item :label="t('step')" prop="amount_step">
          <el-input-number v-model="form.amount_step" :min="0"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>

        <!-- 期限 -->
        <el-form-item :label="t('deadline')" prop="term">
          <el-input-number v-model="form.term"
                           :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>
        <el-form-item :label="t('periodUnit')" prop="term_unit">
          <el-select v-model="form.term_unit" :placeholder="t('pleaseSelect')" :disabled="isView">
            <el-option
              v-for="item in termUnitList"
              :key="item.value"
              :label="item.label"
              :disabled="item.disabled"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 期数 -->
        <el-form-item :label="t('period')" prop="total_period">
          <el-input-number v-model="form.total_period" :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>

        <!-- 总费用配置 -->
        <el-card v-if="form.total_period > 0" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>{{ t('totalFeeConfig') }}</span>
          </div>
          <el-form-item
            v-for="(item, index) in form.total_fee_rate"
            :key="index"
            :label="`${t('di')}${item.period_num}${t('qi')}`"
            :class="{ 'first-period': item.period_num === 1 }"
          >
            <el-row :gutter="20">
              <el-col :span="10">
                <el-form-item :label="t('ratePercent')" :prop="`total_fee_rate.${index}.rate`"
                              :rules="{ required: true, validator: createRateValidator(t('interestRate')), trigger: 'blur' }">
                  <el-input-number v-model="item.rate" :precision="cusPrecision" :disabled="isView"
                                   :placeholder="t('pleaseInput')"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item :label="t('dayCount')" :prop="`total_fee_rate.${index}.period_day`"
                              :rules="{ required: true, validator: createNumberValidator($t('dayCount')), trigger: 'blur' }">
                  <el-input-number v-model="item.period_day" disabled
                                   :placeholder="t('pleaseInput')"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
        </el-card>

        <!-- 每期服务费比例配置 -->
        <el-card v-if="form.total_period > 0" class="box-card every-period-config" shadow="never">
          <div slot="header" class="clearfix">
            <span>{{ t('periodServiceFeeConfig') }}</span>
          </div>
          <el-form-item
            v-for="(item, index) in form.period_service_fee_rate"
            :key="index"
            :label="`${t('di')}${item.period_num}${t('qi')}`"
            :prop="`period_service_fee_rate[${index}].rate`"
            :class="{ 'first-period': item.period_num === 1 }"
            :rules="{ required: true, validator: createRateValidator(t('serviceFeePercent')), trigger: 'blur' }"
          >
            <el-input v-model="item.rate" :placeholder="t('pleaseInput')" :disabled="isView" :precision="cusPrecision">
              <template #append>%</template>
            </el-input>
          </el-form-item>
        </el-card>

        <!-- 服务费 -->
        <el-form-item :label="t('serviceFeeRate')" prop="service_fee_rate">
          <el-input v-model="form.service_fee_rate" :placeholder="t('pleaseInput')" :disabled="isView"
                    :precision="cusPrecision">
            <template #append>%</template>
          </el-input>
        </el-form-item>
        <!-- 利息 -->
        <el-form-item :label="t('interestRate')" prop="interest_rate">
          <el-input v-model="form.interest_rate" :placeholder="t('pleaseInput')" :disabled="isView"
                    :precision="cusPrecision">
            <template #append>%</template>
          </el-input>
        </el-form-item>

        <!-- 是否允许提前还款 -->
        <!--        <el-form-item label="提前还款" prop="apply_prepay">
                  <el-select v-model="form.apply_prepay" placeholder="请选择" :disabled="isView">
                    <el-option label="否" :value="0"></el-option>
                    <el-option label="是" :value="1"></el-option>
                  </el-select>
                </el-form-item>-->

        <!-- 展期费率 -->
        <!--        <el-form-item label="展期费率" prop="rollover_fee_rate">
                  <el-input v-model="form.rollover_fee_rate" placeholder="请输入展期费率" :disabled="isView"
                            :precision="cusPrecision">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>-->

        <!-- 数据费 -->
        <el-form-item :label="t('dataFee')" prop="data_cost">
          <el-input-number v-model="form.data_cost" :min="0" :disabled="isView"
                           :placeholder="t('pleaseInput')"></el-input-number>
        </el-form-item>

        <!-- 还款前收费日 -->
        <!--        <el-form-item label="还款前收费日" prop="pre_repay_charge_day">
                  <el-input-number v-model="form.pre_repay_charge_day" :min="0" :disabled="isView"
                                   placeholder="请输入还款前收费日"></el-input-number>
                </el-form-item>-->

        <!-- 开始展期天数 -->
        <!--        <el-form-item label="开始展期天数" prop="rollover_day">
                  <el-input-number v-model="form.rollover_day" :disabled="isView" :min="0"
                                   placeholder="请输入开始展期天数"></el-input-number>
                </el-form-item>-->

        <!-- 逾期利率配置 -->
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>{{ t('overdueFeeConfig') }}</span>
            <el-button v-show="!isView" style="float: right; padding: 3px 0" type="text" @click="addOverdueConfig">
              {{ t('add') }}
            </el-button>
          </div>
          <el-row :gutter="10" style="margin-top: 30px;"
                  v-for="(config, index) in form.overdue_interest_rate_config"
                  :key="index">
            <!-- 最小天数 -->
            <el-col :span="7">
              <el-form-item
                label-width="120"
                :label="t('minDayCount')"
                :prop="`overdue_interest_rate_config.${index}.overdue_day_min`"
                :rules="{ required: true, validator: createNumberValidator(t('dayCount')), trigger: 'blur' }">
                <el-input v-model="config.overdue_day_min" :min="0"
                          :placeholder="t('pleaseInput')" :disabled="isView"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- 最大天数 -->
            <el-col :span="7">
              <el-form-item
                label-width="120"
                :label="t('maxDayCount')"
                :prop="`overdue_interest_rate_config.${index}.overdue_day_max`"
                :rules="{ required: true, validator: createNumberValidator(t('dayCount')), trigger: 'blur' }">
                <el-input v-model="config.overdue_day_max" :placeholder="t('pleaseInput')" :disabled="isView"
                ></el-input>
              </el-form-item>
            </el-col>
            <!-- 每天利率 -->
            <el-col :span="7">
              <el-form-item
                label-width="120"
                :label="t('everyDayInterestRate')"
                            :prop="`overdue_interest_rate_config.${index}.rate`"
                            :rules="{ required: true, validator: createRateValidator(t('interestRate')), trigger: 'blur' }">
                <el-input v-model="config.rate" :precision="cusPrecision" :placeholder="t('pleaseInput')"
                          :disabled="isView"
                >
                  <template #append>%</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button v-show="!isView" type="danger" @click="removeOverdueConfig(index)"
                         :disabled="form.overdue_interest_rate_config.length <= 1">
                {{ t('delete') }}
              </el-button>
            </el-col>
          </el-row>
        </el-card>

        <!-- 提前还款配置 -->
        <!--
                <el-card class="box-card" style="margin-top: 20px" shadow="never">
                  <div slot="header" class="clearfix">
                    <span>提前还款配置</span>
                  </div>
                  <el-row :gutter="20" style="margin-top: 20px">
                    &lt;!&ndash; 最小天数 &ndash;&gt;
                    <el-col :span="8">
                      <el-form-item label="最小天数" prop="prepay_fee_rate.pre_day_min">
                        <el-input-number v-model="form.prepay_fee_rate.pre_day_min" :min="0" :disabled="isView"
                                         placeholder="请输入最小提前还款天数"></el-input-number>
                      </el-form-item>
                    </el-col>
                    &lt;!&ndash; 最大天数 &ndash;&gt;
                    <el-col :span="8">
                      <el-form-item label="最大天数" prop="prepay_fee_rate.pre_day_max">
                        <el-input-number v-model="form.prepay_fee_rate.pre_day_max" :disabled="isView"
                                         placeholder="请输入最大提前还款天数"></el-input-number>
                      </el-form-item>
                    </el-col>
                    &lt;!&ndash; 每天利率 &ndash;&gt;
                    <el-col :span="8">
                      <el-form-item label="利率" prop="prepay_fee_rate.rate">
                        <el-input v-model="form.prepay_fee_rate.rate" :precision="cusPrecision" :disabled="isView"
                                  placeholder="请输入提前还款利率">
                          <template #append>%</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-card>
        -->

        <!-- 提交按钮 -->
        <el-form-item v-show="!isView">
          <el-button class="btn-submit" type="primary" @click="handleSubmit">{{ t('submit') }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElInput,
  ElInputNumber,
  ElButton,
  ElRow,
  ElCol,
  ElMessage
} from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { saveRepayScheme } from '@/api/repayScheme'
import { useRoute, useRouter } from 'vue-router'
import useRepaySchemeStore from '@/stores/repaySchemeStore'

import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()
import { formRules, createNumberValidator, createRateValidator } from './rules'

const repaySchemeStore = useRepaySchemeStore()
const route = useRoute()
const router = useRouter()
let loading = ref(false)
const { productList } = storeToRefs(repaySchemeStore)
let isView = false
onMounted(() => {
  repaySchemeStore.getProductList()
  if (route.query && route.query.item) {
    isView = true
    const item = JSON.parse(route.query.item)
    fillFormWithDetails(item)
  }
})

const fillFormWithDetails = (details) => {
  form.product_id = details.product_id
  form.pay_config_id = details.id
  form.loan_num_max = details.loan_num_max
  form.loan_num_min = details.loan_num_min
  form.amount_max = details.amount_max
  form.amount_min = details.amount_min
  form.amount_step = details.amount_step
  form.term = details.term
  form.total_period = details.total_period
  form.service_fee_rate = details.service_fee_rate
  form.total_fee_rate = details.total_fee_rate
  form.interest_rate = details.interest_rate
  form.apply_prepay = details.apply_prepay
  // form.rollover_fee_rate = details.rollover_fee_rate
  form.data_cost = details.data_cost
  form.rollover_day = details.rollover_day
  // form.pre_repay_charge_day = details.pre_repay_charge_day
  form.overdue_interest_rate_config = details.overdue_interest_rate_config
  form.period_service_fee_rate = details.period_service_fee_rate
  form.prepay_fee_rate = details.prepay_fee_rate
}

const cusPrecision = 2
const rules: FormRules = formRules

const termUnitList = [{
  label: t('day'),
  value: 1
}, {
  label: t('month'),
  value: 2,
  disabled: true
}]

const formRef = ref<FormInstance>()
const form = reactive({
  product_id: null,
  pay_config_id: 0,
  loan_num_min: -1,
  loan_num_max: -1,
  amount_max: null,
  amount_min: null,
  amount_step: null,
  term: null,
  term_unit: 1,
  total_period: null,
  service_fee_rate: '',
  total_fee_rate: [],
  interest_rate: '',
  apply_prepay: 0,
  // rollover_fee_rate: '',
  data_cost: 0,
  rollover_day: 0,
  // pre_repay_charge_day: 0,
  overdue_interest_rate_config: [{
    overdue_day_min: 0,
    overdue_day_max: 0,
    rate: null
  }],
  period_service_fee_rate: [],
  prepay_fee_rate: {
    pre_day_min: '0',
    pre_day_max: '0',
    rate: null
  }
})

// 单独监听form.term的变化
watch(
  () => form.term,
  (newTerm) => {
    // 如果是查看模式或者总期数为0，不进行任何操作
    if (isView || form.total_period === 0) {
      return
    }
    // 只更新total_fee_rate数组中的period_day
    form.total_fee_rate.forEach((item) => {
      item.period_day = newTerm / form.total_period
    })
  }
)
watch(() => form.total_period, (newVal) => {
  if (isView) {
    return
  }
  form.total_fee_rate = Array.from({ length: newVal }, (_, i) => ({
    period_num: i + 1,
    rate: null,
    period_day: form.term ? form.term / form.total_period : null
  }))
  form.period_service_fee_rate = Array.from({ length: newVal }, (_, index) => ({
    period_num: index + 1,
    rate: null
  }))
})

// 添加配置
const addOverdueConfig = () => {
  if (form.overdue_interest_rate_config.length < 3) {
    form.overdue_interest_rate_config.push({
      overdue_day_min: 0,
      overdue_day_max: 0,
      rate: null
    })
  }
}

// 删除配置
const removeOverdueConfig = (index) => {
  if (form.overdue_interest_rate_config.length > 1) {
    form.overdue_interest_rate_config.splice(index, 1)
  }
}

const handleSubmit = () => {
  if (!formRef.value) return
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const formattedData = {
        ...form,
        service_fee_rate: `${parseFloat(form.service_fee_rate).toFixed(4)}`
      }
      if (formattedData.hasOwnProperty('pay_config_id')) {
        delete formattedData['pay_config_id']
      }
      if (formattedData.hasOwnProperty('pre_repay_charge_day')) {
        delete formattedData['pre_repay_charge_day']
      }
      if (formattedData.hasOwnProperty('apply_prepay')) {
        delete formattedData['apply_prepay']
      }
      if (formattedData.hasOwnProperty('prepay_fee_rate')) {
        delete formattedData['prepay_fee_rate']
      }
      if (formattedData.hasOwnProperty('rollover_day')) {
        delete formattedData['rollover_day']
      }
      if (formattedData.hasOwnProperty('rollover_fee_rate')) {
        delete formattedData['rollover_fee_rate']
      }
      // 校验总期限能被总期数能整除
      if ((form.total_period && form.term) && form.total_period > 0 && form.term % form.total_period !== 0) {
        ElMessage.error(t('deadlineMustBeDivider'))
        return
      }
      // 校验历史最低和最高次数
      if (form.loan_num_max < form.loan_num_min) {
        ElMessage.error(t('maxCountMustBeBiggerThanMinCount'))
        return
      }
      if ((form.amount_max && form.amount_min) && (form.amount_max < form.amount_min)) {
        ElMessage.error(t('maxAmountMustBeBiggerThanMinAmount'))
        return
      }
      // 校验逾期利率配置
      for (let i = 0; i < form.overdue_interest_rate_config.length - 1; i++) {
        const currentConfig = form.overdue_interest_rate_config[i]
        if (parseInt(currentConfig.overdue_day_min) >= parseInt(currentConfig.overdue_day_max)) {
          ElMessage.error(`${t('overdueFeeConfigDi')}${i + 1}${t('overdueFeeConfigHou')}`)
          return
        }
        const nextConfig = form.overdue_interest_rate_config[i + 1]
        if (parseInt(currentConfig.overdue_day_max) >= parseInt(nextConfig.overdue_day_min)) {
          ElMessage.error(`${t('overdueFeeConfigDi')}${i + 2}${t('overdueFeeConfigMiddle')}${i + 1}${t('overdueFeeConfigMiddleHou')}`)
          return
        }
      }
      // 校验overdue_interest_rate_config最后一项的最大和最小值
      const lastOverdueConfig = form.overdue_interest_rate_config[form.overdue_interest_rate_config.length - 1]
      console.log('lastOverdueConfig:', lastOverdueConfig)
      if (parseInt(lastOverdueConfig.overdue_day_min) >= parseInt(lastOverdueConfig.overdue_day_max)) {
        ElMessage.error(t('overdueFeeConfigMaxDayMustBiggerThanMinDay'))
        return
      }
      console.log('提交的表单数据:', formattedData)
      loading.value = true
      saveRepayScheme(formattedData).then(() => {
        ElMessage.success(t('saveSuccess'))
        router.push({ name: 'schemeList' })
      }).catch(() => {
        ElMessage.error(t('saveFail'))
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('表单验证失败')
    }
  })
}
</script>

<style scoped lang="scss">
.add_container {
  background-color: white;
  padding: 30px;
  margin: 20px 20px 10px 0px;
  border: 1px solid #ebeef5;

  .every-period-config {
    margin: 20px 0;
  }

  .btn-submit {
    width: 180px;
    margin-top: 38px;
  }
}

.add_container .el-select,
.add_container .el-input,
.add_container .el-input-number {
  width: 300px;

}

.first-period {
  margin-top: 20px;
}
</style>
